package com.nic.view.adapter;


import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.nic.view.R;
import com.nic.view.activity.PhotoPreviewActivity;
import com.nic.view.activity.TakePhotoActivity;
import com.nic.view.util.glide.GlideUtil;
import com.nic.view.widget.NiceImageView;

import java.io.Serializable;

/**
 * Created by Administrator on 2018/5/17.
 */

public class PhotoAdapter extends CommonAdapter<String> {
    private int tag;

    @Override
    public View getBindView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, null);
            holder = new ViewHolder();
            holder.imageView = (NiceImageView) convertView.findViewById(R.id.iv_photo);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String path = getList().get(position);
        holder.imageView.setTag(R.id.glide_image_id, path);
        String tag = (String) holder.imageView.getTag(R.id.glide_image_id);
        if (!TextUtils.isEmpty(tag) && tag == path) {
            GlideUtil.getInstance().loadSmall(path, holder.imageView);
            holder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    jumpPreview(parent);
                }
            });
        } else {
            GlideUtil.getInstance().clear(holder.imageView);
            holder.imageView.setImageResource(R.mipmap.ic_add_pic);
            holder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TakePhotoActivity.jumpTo((Activity) parent.getContext(), "" + getTag(), getList(), 43533);
                }
            });
        }
        return convertView;
    }

    public void remove(int position) {
        getList().remove(position);
        notifyDataSetChanged();
    }

    private void jumpPreview(ViewGroup parent) {
        Intent intent = new Intent(parent.getContext(), PhotoPreviewActivity.class);
        intent.putExtra(PhotoPreviewActivity.LIST, (Serializable) getList());
        parent.getContext().startActivity(intent);
    }

    public void setTag(int tag) {
        this.tag = tag;
    }

    public int getTag() {
        return tag;
    }

    class ViewHolder {
        NiceImageView imageView;
    }

}
